<template>
	<base-popup
		titleT="feed.description"
		:show="!!feedStore.descriptionOrderNo"
		class="min-h-[80vh]"
		@open="onOpen"
		@close="onClose">
		<base-loading-box class="flex-1" :isEmpty="isEmpty" :loading="loading" :error="error">
			<div v-if="data" class="flex-1 flex flex-col justify-between py-5 px-9 relative">
				<div class="flex-1 overflow-auto">
					<betting-record :data="data">
						<template #header>
							<base-textarea
								ref="textareaRef"
								v-model="content"
								:placeholder="$t('feed.descriptionPH', [bettingConfigStore.reasonMinChars])"
								:maxlength="1000"
								:lengthClass="
									content.trim().length >= bettingConfigStore.reasonMinChars ? '!text-success' : ''
								"
								class="h-[180px] bg-transparent" />
						</template>
					</betting-record>
				</div>
			</div>
		</base-loading-box>
		<template v-if="data" #footer>
			<div class="pt-2 pb-8 px-9">
				<base-button
					type="primary"
					:disabled="submitDisabled"
					:loading="submitLoading"
					block
					@click="submit">
					{{ $t('action.save') }}
				</base-button>
			</div>
		</template>
	</base-popup>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { BasePopup, BaseTextarea, BaseButton, BaseLoadingBox } from '@/components/base'
import { BettingRecord } from '@/components/betting'
import { useAppStore, useFeedStore, useBettingConfigStore, useBetslipStore } from '@/store'
import { updateFeeds } from '@/api/feed'
import { getBetResultDetail } from '@/api/betting'
import { useRequest } from '@/hooks'
import { FeedType } from '@/types'
import { t } from '@/utils'

defineOptions({ name: 'ViewsFeedDescription' })

const appStore = useAppStore()
const feedStore = useFeedStore()
const betslipStore = useBetslipStore()
const bettingConfigStore = useBettingConfigStore()

const content = ref('')

const textareaRef = ref<any>(null)

const { run, data, loading, error, isEmpty, reset } = useRequest<FeedType>(getBetResultDetail, {
	onSuccess: () => {
		setTimeout(() => {
			textareaRef.value?.focus()
		})
	}
})

const { run: runSubmit, loading: submitLoading } = useRequest(updateFeeds, {
	showSuccess: t('feed.descriptionSuccess'),
	onSuccess: () => {
		betslipStore.removeSuccess(feedStore.descriptionOrderNo)
		if (data.value) {
			feedStore.setDescription(feedStore.descriptionOrderNo, content.value)
		}
		onClose()
	}
})

const onOpen = () => {
	run({
		orderNo: feedStore.descriptionOrderNo,
		oddsStyle: appStore.odds,
		locale: appStore.lang,
		ignoreExt: true
	})
}

const onClose = () => {
	feedStore.showDescription('')
	content.value = ''
	reset()
}

const submitDisabled = computed(
	() => content.value.trim().length === 0 || content.value.trim().length > 1000
)

const submit = () =>
	runSubmit({ orderNo: feedStore.descriptionOrderNo, content: content.value.trim() })
</script>
